package cn.accp.mvc.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class UserInterceptor implements HandlerInterceptor{
	
	//允许哪些url不被拦截，哪些被拦截
	private List<String> allowedPass;
	
	//在DispatcherServlet处理之后执行---清理工作
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object object, Exception exception)
			throws Exception {
	}
	//在请求处理的方法之后执行
	public void postHandle(HttpServletRequest request, HttpServletResponse response,
			Object object, ModelAndView modelAndView) throws Exception {
	}
	//在请求处理的方法之前执行过
	//如果返回true那么执行下一个拦截器，
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object object) throws Exception {
		//先判断session中是否存在
		Object user = request.getSession().getAttribute("users");
		if (user != null) {
			return true;
		}
		//获取当前url
		String url = request.getRequestURL().toString();
		for (String  temp : allowedPass) {
			if(url.endsWith(temp)){
				return true;
			}
		}
		response.sendRedirect(request.getContextPath()+"/index.jsp");
		return false;
	}
	public void setAllowedPass(List<String> allowedPass) {
		this.allowedPass = allowedPass;
	}

}
